<?php

namespace app\api\controller\v1;

use app\common\model\UserCardOrders;
use think\Db;
use think\Exception;
use think\Request;
use WechatPay\GuzzleMiddleware\Util\AesUtil;

class Notify
{
    /**
     * 微信支付回调
     * */
    public function weChatOrderNotify()
    {
        try {
            $input = Request::instance()->getInput();
            if (empty($input)) {
                throw new Exception('未接受到回调通知参数');
            }
            // $order = '{"id":"76be306f-4c1a-5855-859c-3d6f3cce1f82","create_time":"2024-04-26T17:16:52+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"4p6qV6muAa9O/pom6yJBiy+djGgqMS7qUPnVlQOz16WWYhvSj+EUHbZ2d2pRyKhc7CV1DbyjpQzMPK2nCZNX7hhPWSv6JLeNC3rQvtJ+BRstMnXF6XpoeASj4y1K+JdGmCH1iMkbfdIBNOC4VNzUIs/afa7L6fZY5bqOzJKI2L+hi4a9l5OKDZiohyiepqaT9sjAdhXg88DZss0j945zOm9TkA50mmCTCsZUlSbLXfjRFVJhX26qw4x5zHYPevUbkdUc09P/6Gil+WBOWXtE6Lgm8nWJVtfUV8mV0wDJLlFMIkrQnXu0mrkEz0sGIBH86k2JKsWEdtnadkRVcSgGAwyEACuRz8ty4VMnrDqaR7vdbUgZ1IAg9KkJtwqV4bCAdJYvtmVc9pOZi5OEz6wFogKAoLg1CyptlRvOa1iWncQZABeJBNQyGGgjC6V2YPVMeqEnSADcffMVO/KZRoxKBblut1jbJTTE+NGWbO5CI1U0VN0WIR6RblZKsri0xf3m8GNxOv5ww18uJw+kZ/7+Dk9qQWP8Dg8YWnaNdyGFoSDGZf2smJM/zmdrgE5omDWTk0n7lKopeVW6Hg==","associated_data":"transaction","nonce":"wAmR8gMHGLOx"}}';
            $order = json_decode($input, true);
            $result = (new AesUtil(config('site.payConfig')['cipher']))->decryptToString($order['resource']['associated_data'], $order['resource']['nonce'], $order['resource']['ciphertext']);
            if (!$result) {
                throw new Exception('回调参数解密失败');
            }
            $result = json_decode($result, true);
            if ($result['trade_state'] == 'SUCCESS') {
                $params = ['order_sn' => $result['out_trade_no']];
                // 查询订单是否存在
                if (!$rows = UserCardOrders::instance()->where($params)->find()) {
                    throw new Exception('订单号：【' . $params['order_sn'] . '】不存在');
                }
                // 订单操作
                if ($this->wxOrderEdit($rows, $result)) {
                    $this->writeLog('订单修改成功', 'success');
                    return json_encode(['code' => 'SUCCESS', 'message' => '成功'], JSON_UNESCAPED_UNICODE);
                }
            }
            throw new Exception('订单修改失败');
        } catch (Exception $exception) {
            $this->writeLog($exception->getMessage());
            return json_encode(['code' => 'FAIL', 'message' => '失败：' . $exception->getMessage()], JSON_UNESCAPED_UNICODE);
        }
    }

    protected function wxOrderEdit($rows, $result)
    {
        Db::startTrans();
        try {
            $save['status'] = 2;
            $save['pay_params'] = json_encode($result, JSON_UNESCAPED_UNICODE);
            $save['pay_time'] = date('Y-m-d H:i:s');
            if ($rows->allowField(true)->save($save)) {
                Db::commit();
                return true;
            }
            throw new Exception('修改订单失败');
        } catch (Exception $exception) {
            $this->writeLog($exception->getMessage());
            Db::rollback();
            return false;
        }
    }

    protected function writeLog($content, $type = 'error')
    {
        $dir = ROOT_PATH . 'runtime' . DS . 'payLogs' . DS . date('Y-m-d');
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        $file = 'pay_error_' . date('Y-m-d') . '.log';
        if ($type == 'error') {
            file_put_contents($dir . DS . $file, '【' . date('Y-m-d H:i:s') . '-error.log】' . $content . "\n", FILE_APPEND);
        } else {
            file_put_contents($dir . DS . $file, '【' . date('Y-m-d H:i:s') . '-success.log】' . $content . "\n", FILE_APPEND);
        }
    }
}